var litems_cache = new Array();
var lisplit_cache = {};

var supp_cache = null;

var uom_cache = null;
var cur_cache = null;

var po_createActionsMenu1 = null;
var po_createActionsMenu2 = null;

function open_create_po(){
	u_hideAllSections();
	u_safeShowElement('createpo_table_container');
	getPOPreferredSuplierList(usr_comp_cache.companyId);
	fetch_uomcurdetails();
	init_pocreate();
	
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_create_po()";
	navigationStateArray.push(functionPointerObj);
	}

}

function fetch_uomcurdetails(){
	var dcmd1 = {
			callback : success_fetchuom,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};
	DWR_PurchaseOrders.getAllUnitOfMeasures(dcmd1);
	
	var dcmd2 = {
			callback : success_fetchcur,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};
	
	
	DWR_PurchaseOrders.getAllCurrencyCodes(dcmd2);
}

function success_fetchuom(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
			uom_cache = dwrresp.objRespOrError;
		}
	}
}

function success_fetchcur(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
			cur_cache = dwrresp.objRespOrError;
		}
	}
}

function init_pocreate() {
	clearnestedDataTable();
	sel_po_cache = null;
	litems_cache = null;
	litems_cache = new Array();
	lisplit_cache = null;
	lisplit_cache = {};
	g_po_num = null;
	poAttachmentArray = new Array();
	var dwrCallMetaData = {
		callback : success_autogentponum,
		exceptionHandler : exception_generic_handler,
		timeout : 100000,
		errorHandler : exception_generic_handler
	};

	DWR_PurchaseOrders.getAutogeneratedOrderNumber("PURCHASE_ORDER",
			dwrCallMetaData);
	dwr.util.setValue('po_createdate', format_date(new Date()));
	dwr.util.setValue('po_compname', usr_comp_cache.companyName);
	dwr.util.setValue('po_deliverycontact', usrname);
	dwr.util.setValue('po_reqby', usrname);
	dwr.util.setValue('po_preparedby', usrname);
	dwr.util.setValue('po_deliveryemail', usremail);
	dwr.util.setValue('po_deliveryphone', usr_profile_cache.workPhone);
	dwr.util.setValue('podeliveryinfo', usr_profile_cache.deliveryInfo);
	dwr.util.setValue('po_totalamt',0);
	dwr.util.setValue('uploadFile','');
	
	
	
	//Populate addresses.
	var baddrArray = new Array();
	var saddrArray = new Array();
	baddrArray.push({ idx: -1 , addr: "Select Billing Address" });
	saddrArray.push({ idx: -1 , addr: "Select Shipping Address" });
	if(usr_comp_cache.locations != null && usr_comp_cache.locations.length > 0){
		for(var kk=0;kk<usr_comp_cache.locations.length;kk++){
			var a = usr_comp_cache.locations[kk].addressLine1 + " " + usr_comp_cache.locations[kk].addressLine2 + " " + usr_comp_cache.locations[kk].city + " " + usr_comp_cache.locations[kk].state + " " + usr_comp_cache.locations[kk].zip;
			var obj = {idx: kk, addr: a};
			if(usr_comp_cache.locations[kk].billingAddress == "Yes"){
				baddrArray.push(obj);
			}
			
			if(usr_comp_cache.locations[kk].shippingAddress == "Yes"){
				saddrArray.push(obj);
			}
		}
	}
	
	dwr.util.removeAllOptions("poBillingAddressDropDown");
	dwr.util.addOptions("poBillingAddressDropDown",baddrArray,"idx","addr");
	
	dwr.util.removeAllOptions("poShippingAddressDropDown");
	dwr.util.addOptions("poShippingAddressDropDown",saddrArray,"idx","addr");
	
	
	create_line_item_table();
	populate_line_item_table();
	assignNestedDataTableComp("lineItem_Table1_PlaceHolder1");
	assignCommentsComponent("commentComponetPlaceHolder1");
	assignAttachmentComponent("attachmentComponetPlaceHolder1");
	dwr.util.setValue('target_comp_comment',"CREATE_PO");
	dwr.util.setValue('target_comp_attachment',"CREATE_PO");
}

var g_po_num = null;

function success_autogentponum(dwrresp) {
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& !isEmptyString(dwrresp.objRespOrError)) {
			g_po_num = dwrresp.objRespOrError;
			dwr.util.setValue('po_genponum', dwrresp.objRespOrError);
		}
	}
}

var find_supp_dlg_instance = null;

function open_findsupplier() {
	/*if (find_supp_dlg_instance == null) {
		find_supp_dlg_instance = new YAHOO.widget.Dialog(
				'find_supplier_dlg_content', {
					width : "300px",
					effect : {
						effect : YAHOO.widget.ContainerEffect.FADE,
						duration : 0.25
					},
					fixedcenter : true,
					modal : false,
					visible : false,
					draggable : false
				});

		var handleCancel = function() {
			this.cancel();
		};

		var handleSelectSupplier = function() {
			// Get selected row from supplier table.
			this.cancel();
		}

		var handleSubmit = function() {
			var details = {};
			details["companyId"] = dwr.util.getValue('supp_num');
			details["companyName"] = dwr.util.getValue('supp_name');
			details["companyTaxId"] = dwr.util.getValue('supp_taxid');
			details["companySSN"] = dwr.util.getValue('supp_ssn');
			find_supplier(details);
		};
		var dlgButtons = [ {
			text : "Search",
			handler : handleSubmit,
			isDefault : true
		}, {
			text : "Select Supplier",
			handler : handleSelectSupplier
		}, {
			text : "Cancel",
			handler : handleCancel
		} ];
		find_supp_dlg_instance.cfg.queueProperty("buttons", dlgButtons);
		find_supp_dlg_instance.render();
	}*/
	//find_supp_dlg_instance.show();
	document.getElementById('find_supplier_dlg_content').style.display = 'none';
	

}

function find_supplier(details) {
	/*var dwrCallMetaData = {
		callback : success_findsupplier,
		exceptionHandler : exception_generic_handler,
		timeout : 100000,
		errorHandler : exception_generic_handler
	};

	DWR_PurchaseOrders.findSupplierInformation(details, dwrCallMetaData);*/
	
	var dwrCallMetaData = {
			callback : successpo_getPreferredSuplierList,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};

		DWR_Register.getPreferredSuplierList(details, dwrCallMetaData);
}

function success_findsupplier(dwrresp) {
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
			/*if (ssr_yui_table_instance == null) {
				create_supplier_results_table();
			}

			// Clear Table.
			clear_supplier_results_table();

			ssr_yui_table_instance.addRows(dwrresp.objRespOrError);*/
			supp_cache = dwrresp.objRespOrError;
			populate_suppDetails();
		}
	}
}

function populate_suppDetails(){
	
	if(supp_cache != null && supp_cache.length > 0){
		var emptyopt = [{companyUniqueIdentifier: null, companyName: "Choose a Supplier"}];
		dwr.util.addOptions("supplierDropDown",emptyopt,"companyUniqueIdentifier","companyName");
		dwr.util.addOptions("supplierDropDown",supp_cache,"companyUniqueIdentifier","companyName");
	}
	
	
}

var ssr_yui_table_instance = null;

function create_supplier_results_table() {
	var ssrcolumnDefs = [ {
		key : "companyName",
		label : "Name"
	}, {
		key : "companyTaxId",
		label : "Tax ID"
	}, {
		key : "companySSN",
		label : "SSN"
	} ];

	var ssrDataSource = new YAHOO.util.DataSource();
	ssrDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
	ssr_yui_table_instance = new YAHOO.widget.DataTable(
			"supp_searchresults_table",
			ssrcolumnDefs,
			ssrDataSource,
			{
				caption : "Click a row to Select Supplier and then click 'Select Supplier'."
			});
	ssr_yui_table_instance.set("selectionMode", "single");
	ssr_yui_table_instance.subscribe("rowClickEvent",
			ssr_yui_table_instance.onEventSelectRow);
	ssr_yui_table_instance.subscribe("rowClickEvent", function(oArgs) {
		var elTarget = oArgs.target;
		var oRecord = this.getRecord(elTarget);
		select_suppplier(oRecord);
	});

}

function clear_supplier_results_table() {
	if (ssr_yui_table_instance !== null) {
		var length = ssr_yui_table_instance.getRecordSet().getLength();
		if (length > 0) {
			ssr_yui_table_instance.deleteRows(0, length);
		}
	}
}

function select_suppplier(oRecord) {
	var suppAddr = oRecord.getData("addressLine1") + ", "
			+ oRecord.getData("addressLine2") + " " + oRecord.getData("city")
			+ " " + oRecord.getData("city") + " " + oRecord.getData("state")
			+ " " + oRecord.getData("zip");
	dwr.util.setValue('supp_comp_id', oRecord
			.getData("companyUniqueIdentifier"))
	dwr.util.setValue('po_suppliername', oRecord.getData("companyName"));
	dwr.util.setValue('po_supplieraddress', "Address of " + suppName + " here");
	dwr.util.setValue('po_supplierpmtterms', "Payment Terms of "
			+ oRecord.getData("companyName") + " here");
}

var add_lineitem_dlg_instance = null;
function open_add_lineitem(e, loc, isnew_item) {
	dwr.util.setValue('li_number', '');
	dwr.util.setValue('li_part', '');
	dwr.util.setValue('li_qty', '');
	dwr.util.setValue('li_unitprice', '');
	dwr.util.setValue('li_currency', '');
	dwr.util.setValue('li_uom', '');
	dwr.util.setValue('li_desc', '');
	if (isnew_item) {
		gen_lineitemNumber();
	} else {
		dwr.util.setValue('li_number', g_curr_litem.orderLineItemNumber);
		dwr.util.setValue('li_part', g_curr_litem.partNumber);
		dwr.util.setValue('li_qty', g_curr_litem.quantity);
		dwr.util.setValue('li_unitprice', g_curr_litem.unitPrice);
		dwr.util.setValue('li_currency', g_curr_litem.unitCurrency.uniqueName);
		dwr.util.setValue('li_uom', g_curr_litem.unitOfMeasure.uniqueName);
		dwr.util.setValue('li_desc', g_curr_litem.lineDescription);
	}

	if (add_lineitem_dlg_instance == null) {
		add_lineitem_dlg_instance = new YAHOO.widget.Dialog(
				'add_lineitem_dlg_content', {
					width : "300px",
					effect : {
						effect : YAHOO.widget.ContainerEffect.FADE,
						duration : 0.25
					},
					fixedcenter : true,
					modal : false,
					visible : false,
					draggable : false
				});
	}
	var btext = "";
	var ahandler = null;

	var handleCancel = function() {
		this.cancel();
	};

	var handleAdd = function() {
		this.cancel();
		create_lineitem_tree();
	};

	var handleChange = function() {
		this.cancel();
		change_item_data();
	}

	if (isnew_item) {
		btext = "Add";
		dwr.util.setValue('lineitem_dlg_header', 'Add Line Item');
		ahandler = handleAdd;

	} else {
		btext = "Change";
		dwr.util.setValue('lineitem_dlg_header', 'Change Line Item');
		ahandler = handleChange;
	}

	var dlgButtons = [ {
		text : btext,
		handler : ahandler,
		isDefault : true
	}, {
		text : "Cancel",
		handler : handleCancel
	} ];
	add_lineitem_dlg_instance.cfg.queueProperty("buttons", dlgButtons);
	add_lineitem_dlg_instance.render();
	document.getElementById('add_lineitem_dlg_content').style.display = 'block';
	add_lineitem_dlg_instance.show();
}

function change_item_data() {
	var node = null;
	var nodeArr = lineitem_tree_view.getNodesByProperty("nodeCustomType",
			"LINE_ITEM");
	if (nodeArr != null) {
		for ( var i = 0; i < nodeArr.length; i++) {
			if (nodeArr[i].data.orderLineItemNumber == g_curr_litem.orderLineItemNumber) {
				node = nodeArr[i];
				break;
			}
		}
	}
	node.data.lineDescription = dwr.util.getValue('li_desc');
	node.data.partNumber = dwr.util.getValue('li_part');
	node.data.quantity = Number(dwr.util.getValue('li_qty'));
	node.data.unitPrice = Number(dwr.util.getValue('li_unitprice'));
	node.data.unitCurrency = {
		uniqueName : dwr.util.getValue('li_currency')
	};
	node.data.unitOfMeasure = {
		uniqueName : dwr.util.getValue('li_uom')
	};
}

function change_lineitemsplit_data() {
	var node = null;
	var nodeArr = lineitem_tree_view.getNodesByProperty("nodeCustomType",
			"LINE_SPLIT");
	if (nodeArr != null) {
		for ( var i = 0; i < nodeArr.length; i++) {
			if (nodeArr[i].data.orderSplitLineItemNumber == g_curr_litem.orderSplitLineItemNumber) {
				node = nodeArr[i];
				break;
			}
		}
	}

	node.data.lineSplitPercent = Number(dwr.util.getValue('lis_percentage'));
	node.data.glAccountNumber = dwr.util.getValue('lis_glaccount');
	node.data.costCenterNumber = dwr.util.getValue('lis_costcenter');
	node.data.projectNumber = dwr.util.getValue('projectNumber');
	node.data.wbsElementNumber = dwr.util.getValue('lis_wbselement');
}

var add_lineitemsplit_dlg_instance = null;
function open_add_lineitemsplit(e, loc, isnew_item) {
	dwr.util.setValue('lis_number', '');
	dwr.util.setValue('lis_percentage', '');
	dwr.util.setValue('lis_glaccount', '');
	dwr.util.setValue('lis_costcenter', '');
	dwr.util.setValue('lis_project', '');
	dwr.util.setValue('lis_wbselement', '');

	if (isnew_item) {
		get_linteitemsplit_num();
	} else {
		dwr.util.setValue('lis_number', g_curr_litem.orderSplitLineItemNumber);
		dwr.util.setValue('lis_percentage', g_curr_litem.lineSplitPercent);
		dwr.util.setValue('lis_glaccount', g_curr_litem.glAccountNumber);
		dwr.util.setValue('lis_costcenter', g_curr_litem.costCenterNumber);
		dwr.util.setValue('lis_project', g_curr_litem.projectNumber);
		dwr.util.setValue('lis_wbselement', g_curr_litem.wbsElementNumber);
	}

	if (add_lineitemsplit_dlg_instance == null) {
		add_lineitemsplit_dlg_instance = new YAHOO.widget.Dialog(
				'add_lineitemsplit_dlg_content', {
					width : "300px",
					effect : {
						effect : YAHOO.widget.ContainerEffect.FADE,
						duration : 0.25
					},
					fixedcenter : true,
					modal : false,
					visible : false,
					draggable : false
				});

	}
	var handleCancel = function() {
		this.cancel();
	};

	var handleAdd = function() {
		this.cancel();
		add_lineitem_splitnode();
	};

	var handleChange = function() {
		this.cancel();
		change_lineitemsplit_data();
	}

	if (isnew_item) {
		btext = "Add";
		dwr.util.setValue('lineitemsplit_dlg_header', 'Add Line Item Split');
		ahandler = handleAdd;

	} else {
		btext = "Change";
		dwr.util.setValue('lineitemsplit_dlg_header', 'Change Line Item Split');
		ahandler = handleChange;
	}

	var dlgButtons = [ {
		text : btext,
		handler : ahandler,
		isDefault : true
	}, {
		text : "Cancel",
		handler : handleCancel
	} ];
	add_lineitemsplit_dlg_instance.cfg.queueProperty("buttons", dlgButtons);
	add_lineitemsplit_dlg_instance.render();
	document.getElementById('add_lineitemsplit_dlg_content').style.display = 'block';
	add_lineitemsplit_dlg_instance.show();
}

function add_lineitem_splitnode() {
	var lis_node = {
		orderNumber : g_po_num,
		orderLineItemNumber : g_curr_litem.orderLineItemNumber,
		orderSplitLineItemNumber : dwr.util.getValue('lis_number'),
		lineSplitPercent : Number(dwr.util.getValue('lis_percentage')),
		glAccountNumber : dwr.util.getValue('lis_glaccount'),
		costCenterNumber : dwr.util.getValue('lis_costcenter'),
		projectNumber : dwr.util.getValue('lis_project'),
		wbsElementNumber : dwr.util.getValue('lis_wbselement')
	};

	/*
	 * var nodeArr = lineitem_tree_view.getNodesByProperty("nodeCustomType",
	 * "LINE_ITEM"); if (nodeArr != null) { for ( var i = 0; i < nodeArr.length;
	 * i++) { if (nodeArr[i].data.orderLineItemNumber ==
	 * g_curr_litem.orderLineItemNumber) { var tnode = new
	 * YAHOO.widget.TextNode(lis_node, nodeArr[i], true);
	 * lineitem_tree_view.render(); break; } } }
	 */

	if (lisplit_cache[g_po_num + "." + g_curr_litem.orderLineItemNumber] == undefined
			|| lisplit_cache[g_po_num + "." + g_curr_litem.orderLineItemNumber] == null) {
		lisplit_cache[g_po_num + "." + g_curr_litem.orderLineItemNumber] = new Array();
	}

	var arr = lisplit_cache[g_po_num + "." + g_curr_litem.orderLineItemNumber];

	arr.push(lis_node);

	li_render_liTable();
}

// var lineitem_tree_view = null;
function create_lineitem_tree() {
	/*
	 * if (lineitem_tree_view == null) { lineitem_tree_view = new
	 * YAHOO.widget.TreeView( "lineitem_tree_container");
	 * lineitem_tree_view.singleNodeHighlight = true;
	 * lineitem_tree_view.subscribe('clickEvent',
	 * lineitem_tree_view.onEventToggleHighlight);
	 * 
	 * lineitem_tree_view.subscribe('dblClickEvent', lineitem_node_clicked); }
	 */
	if (litems_cache == null) {
		litems_cache = new Array();
	}

	var li_node = {
		orderNumber : g_po_num,
		orderLineItemNumber : g_curr_li_num,
		lineDescription : dwr.util.getValue('li_desc'),
		partNumber : dwr.util.getValue('li_part'),
		quantity : Number(dwr.util.getValue('li_qty')),
		unitPrice : Number(dwr.util.getValue('li_unitprice')),
		unitCurrency : {
			uniqueName : dwr.util.getValue('li_currency')
		},
		unitOfMeasure : {
			uniqueName : dwr.util.getValue('li_uom')
		}
	// ,
	// label : "Line Item--> " + g_po_num + "#" + g_curr_li_num,
	// nodeCustomType : "LINE_ITEM"

	};

	/*
	 * var tnode = new YAHOO.widget.TextNode(li_node,
	 * lineitem_tree_view.getRoot(), false); lineitem_tree_view.render();
	 * lineitem_tree_view.show(); tnode = null;
	 */

	litems_cache.push(li_node);

	li_render_liTable();
}

function li_render_liTable() {
	// Clear device details
	dwr.util.removeAllRows("lineitems_table_tbody", {
		filter : function(tr) {
			return (tr.id != "lineietem_table_tbody_pattern");
		}
	});

	if (litems_cache != null && litems_cache.length > 0) {
		for ( var i = 0; i < litems_cache.length; i++) {
			var litem = litems_cache[i];
			// create the id
			var litmid = g_po_num + "." + litem.orderLineItemNumber + '';

			// create the clone for the pattern
			dwr.util.cloneNode('lineietem_table_tbody_pattern', {
				idSuffix : litmid
			});
			dwr.util.setValue('lit_linum' + litmid, litem.orderLineItemNumber);

			if (!isEmptyString(litem.partNumber)) {
				dwr.util.setValue('lit_ptnum' + litmid, litem.partNumber);
			} else {
				dwr.util.setValue('lit_ptnum' + litmid, 'Not Available');
			}

			if (!isEmptyString(litem.quantity)) {
				dwr.util.setValue('lit_qty' + litmid, litem.quantity);
			} else {
				dwr.util.setValue('lit_qty' + litmid, '0');
			}

			if (!isEmptyString(litem.lineDescription)) {
				dwr.util.setValue('lit_desc' + litmid, litem.lineDescription);
			} else {
				dwr.util.setValue('lit_desc' + litmid, 'Not Available');
			}

			if (litem.unitOfMeasure != null
					&& !isEmptyString(litem.unitOfMeasure.uniqueName)) {
				dwr.util.setValue('lit_uom' + litmid,
						litem.unitOfMeasure.uniqueName);
			} else {
				dwr.util.setValue('lit_uom' + litmid, 'Not Available');
			}

			if (!isEmptyString(litem.unitPrice)) {
				dwr.util.setValue('lit_uprice' + litmid, litem.unitPrice);
			} else {
				dwr.util.setValue('lit_uprice' + litmid, '0');
			}

			if (litem.unitCurrency != null
					&& !isEmptyString(litem.unitCurrency.uniqueName)) {
				dwr.util.setValue('lit_curr' + litmid,
						litem.unitCurrency.uniqueName);
			} else {
				dwr.util.setValue('lit_curr' + litmid, 'Not Available');
			}

			dwr.util.setValue('lit_litotal' + litmid, Number(dwr.util
					.getValue('lit_uprice' + litmid))
					* Number(dwr.util.getValue('lit_qty' + litmid)) + '');

			document.getElementById('lineietem_table_tbody_pattern' + litmid).style.display = 'table-row';

			var li_splits = lisplit_cache[g_po_num + "."
					+ g_curr_litem.orderLineItemNumber];

			if (li_splits && li_splits != null && li_splits.length > 0) {
				for ( var j = 0; j < li_splits.length; j++) {
					var split = li_splits[j];
					var splitid = "." + split.orderSplitLineItemNumber + "";
					dwr.util.cloneNode('table_lisplit_pattern' + litmid, {
						idSuffix : splitid
					});
					dwr.util.setValue('lispl_number' + litmid + splitid,
							split.orderSplitLineItemNumber);
					dwr.util.setValue('lispl_percentage' + litmid + splitid,
							split.lineSplitPercent);
					dwr.util.setValue('lispl_glaccount' + litmid + splitid,
							split.glAccountNumber);
					dwr.util.setValue('lispl_costcenter' + litmid + splitid,
							split.costCenterNumber);
					dwr.util.setValue('lispl_project' + litmid + splitid,
							split.projectNumber);
					dwr.util.setValue('lispl_wbselement' + litmid + splitid,
							split.wbsElementNumber);
					document.getElementById('table_lisplit_pattern' + litmid
							+ splitid).style.display = 'table-row';
				}
			}
		}
	}
}

var g_curr_litem = null;
function lineitem_node_clicked(oArgs) {
	g_curr_litem = oArgs.node.data;
	show_node_options(g_curr_litem.nodeCustomType);
}

var g_curr_li_num = null;
function gen_lineitemNumber() {
	g_curr_li_num = null;
	var dwrCallMetaData = {
		callback : success_autogentlinum,
		exceptionHandler : exception_generic_handler,
		timeout : 100000,
		errorHandler : exception_generic_handler
	};

	DWR_PurchaseOrders
			.getAutogeneratedOrderNumber("LINE_ITEM", dwrCallMetaData);
}

function success_autogentlinum(dwrresp) {
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& !isEmptyString(dwrresp.objRespOrError)) {
			g_curr_li_num = dwrresp.objRespOrError;
			dwr.util.setValue('li_number', dwrresp.objRespOrError, {
				escapeHtml : false
			});
		}
	}
}

function show_node_options(type) {
	var dstr = null;
	var handleChangeItem = null;
	var handleRemoveItem = null;
	if (type == "LINE_ITEM") {
		dstr = "Line Item";
		handleChangeItem = function() {
			this.cancel();
			open_add_lineitem(false);
		}

		handleRemoveItem = function() {
			remove_line_item();
			this.cancel();
		}
	} else if (type == "LINE_SPLIT") {
		dstr = "Line Split";
		handleChangeItem = function() {
			this.cancel();
			open_add_lineitemsplit(false);
		}

		handleRemoveItem = function() {
			remove_line_split();
			this.cancel();
		}
	} else {
		return;
	}

	var node_options_dlg = new YAHOO.widget.SimpleDialog("options_dlg_content",
			{
				width : "300px",
				fixedcenter : true,
				visible : false,
				draggable : false,
				close : true,
				text : "What do you want to Do?",
				icon : YAHOO.widget.SimpleDialog.ICON_HELP,
				constraintoviewport : true
			});

	var handleCancel = function() {
		this.cancel();
	}
	var dlgButtons = [ {
		text : "Change " + dstr + " Details",
		handler : handleChangeItem
	}, {
		text : "Remove " + dstr + " Details",
		handler : handleRemoveItem
	} ];
	if (type == "LINE_ITEM") {
		var handleAddSplit = function() {
			this.cancel();
			open_add_lineitemsplit(true);
		};
		dlgButtons.push( {
			text : "Add Line Split",
			handler : handleAddSplit
		})
	}
	dlgButtons.push( {
		text : "Cancel",
		handler : handleCancel
	});
	node_options_dlg.cfg.queueProperty("buttons", dlgButtons);
	node_options_dlg.render();
	node_options_dlg.show();
	document.getElementById('options_dlg_content').style.display = 'block';
}

function remove_line_item() {
	alert("TODO");
	/*
	 * var nodeArr = lineitem_tree_view.getNodesByProperty("nodeCustomType",
	 * "LINE_ITEM"); if (nodeArr != null) { for ( var i = 0; i < nodeArr.length;
	 * i++) { if (nodeArr[i].data.orderLineItemNumber ==
	 * g_curr_litem.orderLineItemNumber) {
	 * lineitem_tree_view.removeNode(nodeArr[i], true);
	 * lineitem_tree_view.render(); break; } } }
	 */
}

function remove_line_split() {
	alert("TODO");
	/*
	 * var nodeArr = lineitem_tree_view.getNodesByProperty("nodeCustomType",
	 * "LINE_SPLIT"); if (nodeArr != null) { for ( var i = 0; i <
	 * nodeArr.length; i++) { if (nodeArr[i].data.orderSplitLineItemNumber ==
	 * g_curr_litem.orderSplitLineItemNumber) {
	 * lineitem_tree_view.removeNode(nodeArr[i], true);
	 * lineitem_tree_view.render(); break; } } }
	 */
}

function get_linteitemsplit_num() {
	var dwrCallMetaData = {
		callback : success_autogentlsnum,
		exceptionHandler : exception_generic_handler,
		timeout : 100000,
		errorHandler : exception_generic_handler
	};

	DWR_PurchaseOrders.getAutogeneratedOrderNumber("LINE_SPLIT",
			dwrCallMetaData);
}

function success_autogentlsnum(dwrresp) {
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& !isEmptyString(dwrresp.objRespOrError)) {
				if(nesteddataTable!= null){
					var selectedRow = selectedRecordForAdd;
					if(selectedRow != null){
						var rec = nesteddataTable.getRecordSet().getRecord(selectedRow);
						if(!rec || !rec._oData || !rec._oData.__NESTED__ || !rec._oData.__NESTED__.dt){ return; }
						var nsrs = rec._oData.__NESTED__.dt.getRecordSet();
						for(var i=0;i<nsrs.getRecords().length;i++){
							var nsrc = nsrs.getRecord(i);
							if(isEmptyString(nsrc.getData("orderSplitLineItemNumber"))){
								nsrs.updateRecordValue(nsrc,"orderSplitLineItemNumber",dwrresp.objRespOrError);
								break;
							}
						}
						
						nesteddataTable.getRecordSet().getRecord(selectedRow)._oData.__NESTED__.dt.render();
					} 
				}
		}
	}
}

function savepo() {
	
	//supplier location.
	var loc_idx = dwr.util.getValue('supplierlocDropDown');
	var suppId = dwr.util.getValue('supplierDropDown');
	var supp_loc = null;
	if(supp_cache != null && supp_cache.length > 0){
	 for(var k=0;k<supp_cache.length;k++){
		 if(supp_cache[k].companyId == suppId){
			 var idx = loc_idx.replace(suppId + ".IDX.");
			 if(!isNaN(Number(idx))){
				 supp_loc = supp_cache[k].locations[Number(idx)];
			 }else{
				 supp_loc = supp_cache[k].locations[0];
			 }
		 }
	 }
	}
	
	var bill_loc = dwr.util.getValue('poBillingAddressDropDown');
	var billa = null;
	if(Number(bill_loc) >=0){
		billa = usr_comp_cache.locations[bill_loc];
	}
	
	var ship_loc = dwr.util.getValue('poShippingAddressDropDown');
	var shipa = null;
	if(Number(ship_loc) >=0){
		shipa = usr_comp_cache.locations[ship_loc];
	}
	
	//build po object and make dwr call.
	var po_obj = {
		orderNumber : g_po_num,
		orderSupplier : dwr.util.getValue('supplierDropDown'),
		supplierLocation : supp_loc,
		orderDate : new Date(),
		orderCompany : usrcompany_uid,
		orderOwner : dwr.util.getValue('po_reqby'),
		orderComposer : dwr.util.getValue('po_preparedby'),
		originatingCompany : usrcompany_uid,
		orderAmount : 0,
		lastModifiedDate : new Date(),
		prevVersionNumber : null,
		nextVersionNumber : null,
		versionNumber : "1",
		changeOrderInitiatedBy : loggedinuser,
		orderPaymentTermId : dwr.util.getValue('po_pmtTermsDropDown'),
		orderLineItems : new Array(),
		orderBillToAddress : billa,
		orderShipToAddress : shipa,
		orderDeliveryContact : dwr.util.getValue('po_deliverycontact'),
		orderContactPhone : dwr.util.getValue('po_deliveryphone'),
		orderContactEmail : dwr.util.getValue('po_deliveryemail')
	};
	
	po_obj = updateObjectWithLineItem(po_obj,g_po_num);

	var nodeArr = null;
	var splitArr = null;

	/*
	 * if (lineitem_tree_view != null) { nodeArr =
	 * lineitem_tree_view.getNodesByProperty("nodeCustomType", "LINE_ITEM");
	 * splitArr = lineitem_tree_view.getNodesByProperty("nodeCustomType",
	 * "LINE_SPLIT"); }
	 */

	
	try{
		var poAtchArr = new Array();
		if(attachmentctr > 0){
			for(var ip=0;ip<attachmentctr;ip++){
				if($('poattachments_check'+ip+'').checked){
					poAtchArr.push(dwr.util.getValue('poaattach_id'+ip+''));
				}
			}
		}
		
		if(poAtchArr.length > 0){
			po_obj.orderAttachmentsId = poAtchArr;
		}
		
		
		var pocmtarr = new Array();
		if(pocomments_ctr > 0){
			for(var iq=0;iq<pocomments_ctr;iq++){
				if($('pocomment_check'+iq+'').checked){
					pocmtarr.push(dwr.util.getValue('pocomment_text'+iq+''));
				}
			}
		}
		
		if(pocmtarr.length > 0){
			po_obj.orderComments = pocmtarr;
		}
	}catch(ex){
		
	}

	var dwrCallMetaData = {
		callback : success_savepo,
		exceptionHandler : exception_generic_handler,
		timeout : 100000,
		errorHandler : exception_generic_handler
	};
alert("Validating...");
	DWR_PurchaseOrders.validate(po_obj, dwrCallMetaData);
	alert("Validated...");
	DWR_PurchaseOrders.createOrSavePurchaseOrder(po_obj, true, dwrCallMetaData);
}

function updateObjectWithLineItem(po_obj,orderNumber){
	po_obj.orderLineItems = new Array();
	if (nesteddataTable != null) {
		nodeArr = nesteddataTable.getRecordSet().getRecords();
		for ( var i = 0; i < nodeArr.length; i++) {
			var data = nodeArr[i].getData();
			var rec = nodeArr[i];
			
			var litem = {};
			
			litem.orderNumber = orderNumber;
			litem.orderLineItemNumber = data.orderLineItemNumber;
			litem.partNumber = data.partNumber;
			litem.quantity = data.quantity;
			litem.lineDescription = data.description;
			litem.uomSymbol = data.unitOfMeasure;
			litem.unitPrice = data.unitPrice;
			litem.unitCurrencySymbol =  data.currency;
			
			
			
			
			
			if(rec != null && rec._oData != null && rec._oData.__NESTED__ != null && rec._oData.__NESTED__.dt != null){
				litem.lineItemSplits = new Array();
				var srecs = rec._oData.__NESTED__.dt.getRecordSet().getRecords();
				if(srecs){
					for(var j=0;j<srecs.length;j++){
						var srec = srecs[i];
						var sdata = srec.getData();
						sdata.orderNumber = g_po_num;
						sdata.orderLineItemNumber = data.orderLineItemNumber;
						litem.lineItemSplits.push(sdata);
					}
				}
			}
			
			
			litem.lineAmount  = (litem.unitPrice * litem.quantity);
			po_obj.orderAmount += litem.lineAmount;
			po_obj.orderLineItems.push(litem);
		}
	}
	
	return po_obj;
}

function success_savepo(dwrresp) {
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& !isEmptyString(dwrresp.objRespOrError)) {
			clearnestedDataTable();
			// send attachment code using YUI connection manager since DWR 2
			// does not support BYTE.set the PO in hidden field and pass it
			//uploadAttachment(dwrresp.objRespOrError);
			 alert("Purchase Order: " + dwrresp.objRespOrError + " created successfully");
			 init_pocreate();
			return;
		}
	}

	alert("Purchase Order could not be created. Please try again.");
}
var attachmentctr = 0;
var poAttachmentArray =  new Array();
function uploadAttachment() {
	var filename = dwr.util.getValue('uploadFile');
	$("poNumberForAttachment").value = dwr.util.getValue('target_comp_attachment_id');
	// which tells Connection Manager this is a file upload form
	YAHOO.util.Connect.setForm('addForm', true);
	$("attachment_Throbber").style.display = "inline";
	var uploadHandler = {
		upload : function(o) {
		var ids = attachmentctr + "";
		dwr.util.cloneNode('poattachments_pattern', {
			idSuffix : ids
		});
		
		$("attachment_Throbber").style.display = "none";
		dwr.util.setValue('poaattach_id'+ids,o.responseText);
		
		$("poattachments_link"+ids).setAttribute("href",'javascript:openAttachmentPanel("http://www.atsocii.com'+o.responseText.split(":")[1]+'");');
		$("poattachments_link"+ids).innerHTML = o.responseText.split(":")[3];
		attachmentctr++;
		$("poattachments_pattern"+ids).style.display = '';
		dwr.util.setValue('uploadFile',"");
		
		}
	};
	YAHOO.util.Connect.asyncRequest('POST', '/addAttachment/', uploadHandler);

}

function po_setselected_litem(radioid) {
	var arr = radioid.split(".");

	for ( var i = 0; i < litems_cache.length; i++) {
		if (litems_cache[i].orderLineItemNumber == arr[1]) {
			g_curr_litem = litems_cache[i];
			break;
		}
	}

	document.getElementById('pocreateactions_menu1').style.visibility = 'visible';
	document.getElementById('pocreateactions_menu2').style.visibility = 'hidden';

}

function po_setselected_litemspl(radioid) {
	document.getElementById('pocreateactions_menu1').style.visibility = 'hidden';
	document.getElementById('pocreateactions_menu2').style.visibility = 'visible';
}

lineItemCounter = 1;
var lineItemData = {orderLineItemNumber:"",partNumber:"",quantity:1,description:"",unitOfMeasure:"",unitPrice:"",currency:"",lineAmount:""}; 
var lineItem_table_instance = null;
var nesteddataTable = null;
YAHOO.widget.DataTable.text = function(elLiner, oRecord, oColumn, oData) {
	var flg = (oColumn.getKey() == "quantity" || oColumn.getKey() == "unitPrice" || oColumn.getKey() == "lineSplitPercent");
	
	if(isEmptyString(oData)){
		elLiner.innerHTML = "<input type='text' size='12' value='' onkeyup='javascript:stripnonnumsonflag(this,"+flg+");' onblur=\"javascript:setYuiTableValue(this.value,'"+ oRecord.getId()+"','"+oColumn.getKey()+"');\">" ;
	}else{
		elLiner.innerHTML = "<input type='text'  size='1' onkeyup='javascript:stripnonnumsonflag(this,"+flg+");'  value='"+oData+"' onblur=\"javascript:setYuiTableValue(this.value,'"+ oRecord.getId()+"','"+oColumn.getKey()+"');\">";
	}
};

YAHOO.widget.DataTable.customCheckBOx = function(elLiner, oRecord, oColumn, oData) {

	
	 if (isLineItemSaved(oRecord)) {
		 elLiner.innerHTML = "<input type='checkbox' disabled>";
	    } else {
	    	elLiner.innerHTML = "<input type='checkbox' >"
	    }
};


function isLineItemSaved(oRecord){

	if(sel_po_cache == null || sel_po_cache.orderLineItems == null){
		return false;

	} else{
		var po =  sel_po_cache;
		var isSaved = false;
		for(var i=0;i<po.orderLineItems.length;i++){
				//if(po.orderLineItems[i].lineItemSplits != null && po.orderLineItems[i].lineItemSplits.length > 0){
					if(oRecord.getData("orderLineItemNumber") == po.orderLineItems[i].orderLineItemNumber){
						isSaved = true;
						break;
					}
				//}
		}
		return isSaved
	}
	}



YAHOO.widget.DataTable.dropDownUnit = function(elLiner, oRecord, oColumn, oData) {
	var innerHtml = "<select id=\"" + oRecord.getId() + "-uom\" onblur=\"javascript:setYuiTableValue(this.value,'"+ oRecord.getId()+"');\" onchange=\"javascript:setYuiTableValue(this.value,'"+ oRecord.getId()+"','"+oColumn.getKey()+"');\"><option value=''>Unit1</option>";
	if(uom_cache != null && uom_cache.length > 0){
		for(var i=0;i<uom_cache.length;i++){
			var str = "<option value='" + uom_cache[i].uniqueName + "'>" + uom_cache[i].uniqueName + " - " + uom_cache[i].description + "</option>";
			innerHtml += str;
			str = null;
		}
	}
	innerHtml += "</select>";
	elLiner.innerHTML = innerHtml ;
	innerHtml = null;
};

YAHOO.widget.DataTable.dropDownCurrency = function(elLiner, oRecord, oColumn, oData) {
	var innerHtml = "<select id=\"" + oRecord.getId() + "-cur\" onblur=\"javascript:setYuiTableValue(this.value,'"+ oRecord.getId()+"');\" onchange=\"javascript:setYuiTableValue(this.value,'"+ oRecord.getId()+"','"+oColumn.getKey()+"');\"><option value=''>USD</option>";
	if(cur_cache != null && cur_cache.length > 0){
		for(var i=0;i<cur_cache.length;i++){
			var str = "<option value='" + cur_cache[i].uniqueName + "'>" +  cur_cache[i].uniqueName + " - " +cur_cache[i].description + "</option>";
			innerHtml += str;
			str = null;
		}
	}
	innerHtml += "</select>";
	elLiner.innerHTML = innerHtml ;
	innerHtml = null;
};

YAHOO.widget.DataTable.splitLineFormatter = function(elLiner, oRecord, oColumn, oData) {
	
        elLiner.innerHTML = "<a href=\"javascript:create_split_line('"+ oRecord.getId()+"');\"  >Add</a>";
};

YAHOO.widget.DataTable.splitLineFormatterForDel = function(elLiner, oRecord, oColumn, oData) {
	var sliId = oRecord.getData("orderSplitLineItemNumber");
	var parentId = oRecord.getData("parentId");
	/*var nestedRecord = null;
	for(var i=0; i<nesteddataTable.getRecordSet().getLength();i++){
		var rec = nesteddataTable.getRecordSet().getRecord(i);
		if(rec.getData("orderLineItemNumber") == liId ){
			nestedRecord = nesteddataTable.getRecordSet().getRecord("orderLineItemNumber");
			break;
		}
		 
	}*/
	if(!isSplitLineItemSaved(sliId)){
		elLiner.innerHTML = "<a href=\"javascript:delete_split_line('"+ oRecord.getId()+"','"+parentId+"');\"  >Delete</a>";
	} else{
		elLiner.innerHTML = "N/A";
	}
};

function isSplitLineItemSaved(sliId){

	if( isEmptyString(sliId)|| sel_po_cache == null || sel_po_cache.orderLineItems == null){
		return false;

	} else{
		var po =  sel_po_cache;
		var isSaved = false;
		for(var i=0;i<po.orderLineItems.length;i++){
			if(po.orderLineItems[i].lineItemSplits != null && po.orderLineItems[i].lineItemSplits.length > 0){
				 for(var j=0;j<po.orderLineItems[i].lineItemSplits.length;j++){
					 if(sliId == po.orderLineItems[i].lineItemSplits[j].orderSplitLineItemNumber){
						 isSaved = true;
						 break;
					 }
				 }
			}
			if(isSaved){
				break;
			}	
		}
		return isSaved
	}
}


YAHOO.widget.DataTable.prototype.deleteRowsBy = function (condition) {
	var start = 0, count = 0, current = 0, 
		recs = this.getRecordSet().getRecords();
						
	while (current < recs.length) {
		if (recs[current] && condition(recs[current].getData())) {
			if (count === 0) {
				start = current;
				//console.log('got one to delete at ' + start);
			} else {
				//console.log('got 1 more to delete');
			}
			count++;
			current++;
		} else {
			if (count) {
				this.deleteRows(start,count);
				count = 0;
				current = start;
			} else {
				current++;
			}
		}
	}
	if (count) {
		this.deleteRows(start,count);
	}
};



function deleteSelectedLineItem(){
	nesteddataTable.deleteRowsBy(function (data) {
		return data.check;
	});
	
}

function stripnonnumsonflag(element,flag){
	if(!flag){
		return;
	}
	try {
		text = element.value;
		if (text != null){
			text = text.replace(/[^0-9][^.][^0-9]/g, "");
			element.value = text;
		}
		event.returnValue = false;
	} catch (exception) {}
}

function setYuiTableValue(value, recordid,col){
	var rs = nesteddataTable.getRecordSet();
	if(rs.getRecord(recordid)){
		rs.updateRecordValue(rs.getRecord(recordid),col,value);
		if(col == "quantity" || col == "unitPrice"){
			var qty = rs.getRecord(recordid).getData("quantity");
			var uprice = rs.getRecord(recordid).getData("unitPrice");
			
			if(!isEmptyString(qty) && !isEmptyString(uprice) && !isNaN(qty) && !isNaN(uprice)){
				var linetotal = Number(qty) * Number(uprice);
				rs.updateRecordValue(rs.getRecord(recordid),"lineAmount",linetotal);
				nesteddataTable.render();
			}
			
			var total = 0;
			for(var q=0;q<rs.getLength();q++){
				var r = rs.getRecord(q);
				var amt = r.getData("lineAmount");
				if(amt && !isNaN(Number(amt))){
					total += amt;
				}
			}
			
			dwr.util.setValue('po_totalamt',total);
		}
		return;
	}else{
		var l1 = rs.getRecords().length;
		
		for(var i=0;i<l1;i++){
			var rec = rs.getRecord(i);
			if(rec != null && rec._oData != null && rec._oData.__NESTED__ != null && rec._oData.__NESTED__.dt != null){
				if(rec._oData.__NESTED__.dt.getRecordSet().getRecord(recordid)){
					rec._oData.__NESTED__.dt.getRecordSet().updateRecordValue(rec._oData.__NESTED__.dt.getRecordSet().getRecord(recordid),col,value);
					break;
				}
			}
		}
	}

}

var lineItemcolumnDefs = [ {
	key : "orderLineItemNumber",
	label : "Line#",
	width : "40px"
	
},

{key:"check", label:"Sel",
formatter:YAHOO.widget.DataTable.customCheckBOx},
{
	key : "partNumber",
	label : "Part#",
	formatter:YAHOO.widget.DataTable.text,
	width : "50px",
	hidden: true
	
}, {
	key : "quantity",
	label : "Qty",
	formatter:YAHOO.widget.DataTable.text
	
},{
	key : "description",
	label : "Description",
	formatter:YAHOO.widget.DataTable.text,
	width : "50px"
} ,{
	key : "unitOfMeasure",
	label : "UnitMeasure",
	formatter: YAHOO.widget.DataTable.dropDownUnit,
	width : "50px"
} ,{
	key : "unitPrice",
	label : "Unit Price",
	formatter:YAHOO.widget.DataTable.text,
	width : "50px"
} ,{
	key : "currency",
	label : "Currency",
	formatter:  YAHOO.widget.DataTable.dropDownCurrency,
	width : "50px"
} ,{
	key : "lineAmount",
	label : "Line Total",
	width : "50px"
} ,  

{key:"button", label:"Split Line", formatter:YAHOO.widget.DataTable.splitLineFormatter}

];

var lineItemDataSource = new YAHOO.util.DataSource();
var splitItemDataSource = new YAHOO.util.DataSource();
var splitEmptyData = {orderSplitLineItemNumber: "", lineSplitPercent: "", glAccountNumber: "", costCenterNumber : "", 
		projectNumber : "", wbsElementNumber: "",parentId:""};
var splitItemColDefs = 			[ {
	key : "orderSplitLineItemNumber",
	label : "Split-Line#",
	width : "50px"
	
}, {
	key : "lineSplitPercent",
	label : "Split %",
	formatter:YAHOO.widget.DataTable.text,
	width : "50px"
}, {
	key : "glAccountNumber",
	label : "GL Account",
	formatter:YAHOO.widget.DataTable.text,
	width : "50px"
},{
	key : "costCenterNumber",
	label : "Cost Center",
	formatter:YAHOO.widget.DataTable.text,
	width : "50px"
	
} ,{
	key : "projectNumber",
	label : "Project",
	formatter:YAHOO.widget.DataTable.text,
	width : "50px"
} ,{
	key : "wbsElementNumber",
	label : "WBS Element",
	formatter:YAHOO.widget.DataTable.text,
	width : "50px"
}  ,
{
	key : "parentId",
	hidden: true
} ,

{
	key : "delete",
	label : "Delete",
	formatter:YAHOO.widget.DataTable.splitLineFormatterForDel,
	width : "50px"
} 

];

function create_line_item_table() {
	if(nesteddataTable == null){
		createNestedDataTable();
	}
}

function clearnestedDataTable(){
	if(nesteddataTable != null && nesteddataTable.getRecordSet() != null && nesteddataTable.getRecordSet().getLength() > 0){
		nesteddataTable.deleteRows(0,nesteddataTable.getRecordSet().getLength());
	}
}
 function populate_line_item_table(){
	var numberOfLineToAdd = 1;
	for(var i=0;i<numberOfLineToAdd;i++){
		nesteddataTable.addRow(lineItemData); 
	}
	
	//Make the DWR call to generate as many line item numbers.
	var dwrCallMetaData = {
			callback : success_populatelineitemsontable,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};

		DWR_PurchaseOrders
				.getAutogeneratedOrderNumberBlock("LINE_ITEM", Number(numberOfLineToAdd),dwrCallMetaData);
}
 
 function success_populatelineitemsontable(dwrresp){
	 if(nesteddataTable != null){
		 if (dwrresp && dwrresp.respCode == 0) {
				if (dwrresp.objRespOrError != null
						&& dwrresp.objRespOrError.length != 0) {
					var records = nesteddataTable.getRecordSet().getRecords();
					var consumed = 0;
					for(var i=0;i<records.length && consumed < dwrresp.objRespOrError.length;i++){
						if(isEmptyString(records[i].getData("orderLineItemNumber"))){
							nesteddataTable.getRecordSet().updateRecordValue(records[i],"orderLineItemNumber",dwrresp.objRespOrError[consumed]);
							consumed++;
						}
					}
				}
			}
		 nesteddataTable.render();
	 }
 }
 
 
 function createNestedDataTable(){
	if(nesteddataTable == null){
		
		nesteddataTable = new YAHOO.widget.NestedDataTable(
			'lineItem_Table1', 
			lineItemcolumnDefs,
			lineItemDataSource,
			splitItemColDefs,
			splitItemDataSource,
			{	
				width: "600px",
				
				// we'll leave the actual loading for later
				initialLoad:false, 
				
				// This function links the master to the nested tables
				generateNestedRequest: function (record) {
					return splitEmptyData;

				}
			}
			
			
			
			// configuration attributes for the nested tables would go here
		);
		
		nesteddataTable.subscribe("radioClickEvent", function(oArgs){
			  var elRadio = oArgs.target;
              var oRecord = this.getRecord(elRadio);
              oRecord.setData("radio",elRadio.checked);
            	  
          });
		
		var highlightEditableCell = function(oArgs) { 
            var elCell = oArgs.target; 
            if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) { 
                this.highlightCell(elCell); 
            } 
        }; 
        
        nesteddataTable.subscribe("checkboxClickEvent", function(oArgs){   
        	var elCheckbox = oArgs.target;
			var newValue = elCheckbox.checked;
			var record = this.getRecord(elCheckbox);
			var column = this.getColumn(elCheckbox);
			record.setData(column.key,newValue);
			if(newValue){
				//nesteddataTable.highlightRow(record);
			} else{
				//nesteddataTable.unHighlightRow(record); //no function for this
			}
            
         }); 
        
     
        
        
        

        
        //nesteddataTable.set("selectionMode", "standard");
        //nesteddataTable.subscribe("rowClickEvent",nesteddataTable.onEventSelectRow);
		nesteddataTable.subscribe("cellMouseoverEvent", highlightEditableCell);
		nesteddataTable.subscribe("cellMouseoutEvent", nesteddataTable.onEventUnhighlightCell);
		nesteddataTable.subscribe("cellClickEvent", nesteddataTable.onEventShowCellEditor);
	}
} 

function create_split_line(oRecordId){
	if(nesteddataTable!= null){
		var selectedRow = oRecordId;
		if(selectedRow != null){
			setTimeout("addEmptySplitRow('" + oRecordId +"')",1000);
			setTimeout("generate_ls_split('" + oRecordId +"')", 1000);
		} else{
			alert("Select a row to Add Split Line Item");
		}
	}
	
}

function delete_split_line(oRecordId,parentId){
	if(nesteddataTable!= null){
		try{
			splitEmptyData.parentId = oRecordId;
			nesteddataTable.getRecordSet().getRecord(parentId)._oData.__NESTED__.dt.deleteRow(oRecordId);
			nesteddataTable.render();
		}catch(ex){}
	}
	
}

function addEmptySplitRow(oRecordId){
	try{
		splitEmptyData.parentId = oRecordId;
		nesteddataTable.getRecordSet().getRecord(oRecordId)._oData.__NESTED__.dt.addRow(splitEmptyData);
		nesteddataTable.render();
	}catch(ex){}
}

var selectedRecordForAdd = null;
function generate_ls_split(oRecordId){
	selectedRecordForAdd = oRecordId;
	var dwrCallMetaData = {
			callback : success_autogentlsnum,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};
	DWR_PurchaseOrders.getAutogeneratedOrderNumber("LINE_SPLIT",
			dwrCallMetaData);

}

function getPOPreferredSuplierList(usrcompany_id){
	var config = {
			callback : successpo_getPreferredSuplierList,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler	
	};
	DWR_Register.getPreferredSuplierList(usrcompany_id,config);
}

function successpo_getPreferredSuplierList(list){
	supp_cache = list.objRespOrError;
	if(supp_cache != null && supp_cache.length > 0){
		dwr.util.removeAllOptions("supplierDropDown");
		var emptyopt = [{companyUniqueIdentifier: null, companyName: "Choose a Supplier"}];
		dwr.util.addOptions("supplierDropDown",emptyopt,"companyUniqueIdentifier","companyName");
		dwr.util.addOptions("supplierDropDown",supp_cache,"companyId","companyName");
	}
}

function onchange_suppselect(dropd){
	var value = dropd[dropd.selectedIndex].value;
	var arr = new Array();
	if(supp_cache != null){
		for(var i=0;i<supp_cache.length;i++){
			if(supp_cache[i].companyId == value){
				dwr.util.removeAllOptions("supplierlocDropDown");
				if(supp_cache[i].locations != null){
					for(var j=0;j<supp_cache[i].locations.length;j++){
						var str = supp_cache[i].locations[j].addressLine1 + " " + supp_cache[i].locations[j].addressLine2 + " " + supp_cache[i].locations[j].city + " " + supp_cache[i].locations[j].state + " " + supp_cache[i].locations[j].zip;
						var idx = value + ".IDX." + j;
						arr.push({str: str, idx: idx});
					}
				}
				//update payment terms
				po_updatePaymentTerm("po_pmtTermsDropDown",supp_cache[i].paymentTerms);
				break;
			}
		}
	}
	
	if(arr.length <= 0){
		arr.push({str: "No Locations found." , idx: "0.IDX.0"});
	}
	
	dwr.util.addOptions("supplierlocDropDown",arr,"idx","str");
}

function po_updatePaymentTerm(dropdownID,paymentTermIds){
	
	var currentList = new Array();
	if(paymentTermIds && paymentTermIds != null){
		for	(var i=0;i<paymentTerms.length;i++){
			var paymentTerm = paymentTerms[i];
			
			for(var j=0;j<paymentTermIds.length;j++){
				var selectedId = paymentTermIds[j];
				if(selectedId == paymentTerm.id){
					currentList.push(paymentTerm);
				} 
			}
		}
	}
	
	if(currentList.length < 1){
		currentList.push({id: "" , desc: "No Payments Terms For Supplier"});
	}
	
	dwr.util.removeAllOptions(dropdownID);
	dwr.util.addOptions(dropdownID, currentList, "id", "desc");
	$(dropdownID).value = currentList[0].id;// select bydefault first value
	
}

function togglePOType(obj){
	if(nesteddataTable == null){
		return;
	}
	if(obj.value == "Service"){
		if(nesteddataTable != null)
		//nesteddataTable.hideColumn("quantity"); 
		nesteddataTable.hideColumn("partNumber"); 
	}

	if(obj.value == "Goods"){
		//nesteddataTable.showColumn("quantity"); 
		nesteddataTable.showColumn("partNumber"); 
	}
}

var pocomments_ctr = 0;
function add_pocomment(){
	var text = dwr.util.getValue('pocommenttextarea');
	if(isEmptyString(trimString(text))){
		alert("Nothing to add from the Comments Text Area.");
		return;
	}
	var ids = pocomments_ctr + "";
	
	dwr.util.cloneNode('pocomments_pattern', {
		idSuffix : ids
	});
	
	dwr.util.setValue("pocomment_text"+ids,text);
	pocomments_ctr++;
	$("pocomments_pattern"+ids).style.display = '';
	dwr.util.setValue('pocommenttextarea',"");
}